package com.demo.数据绑定底层演示;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.web.bind.ServletRequestDataBinder;
import org.springframework.web.bind.ServletRequestParameterPropertyValues;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.context.request.ServletWebRequest;
import org.springframework.web.method.support.InvocableHandlerMethod;
import org.springframework.web.servlet.mvc.method.annotation.ServletRequestDataBinderFactory;

public class TestServletDataBinderFactory {
	
	public static void main(String[] args) throws Exception {
		MockHttpServletRequest request = new MockHttpServletRequest();
		request.setParameter("birthday", "1999|01|02");
		request.setParameter("address.name", "西安");
		User target = new User();
		InvocableHandlerMethod method = new InvocableHandlerMethod(new MyController(), MyController.class.getMethod("aaa", WebDataBinder.class));
		List<InvocableHandlerMethod> binderMethods = new ArrayList<InvocableHandlerMethod>() {{
			add(method);
		}};
		ServletRequestDataBinderFactory factory = new ServletRequestDataBinderFactory(binderMethods, null);
		WebDataBinder dataBinder = factory.createBinder(new ServletWebRequest(request), target, "user");
		dataBinder.bind(new ServletRequestParameterPropertyValues(request));
		System.out.println(target);
	}
	
	static class MyController {
		@InitBinder
		public void aaa(WebDataBinder dataBinder) {
			// 扩展dataBinder的转换器
			dataBinder.addCustomFormatter(new MyDateFormatter());
		}
	}

	public static class User {
		private Date birthday;
		private Address address;
		public Date getBirthday() {
			return birthday;
		}
		public void setBirthday(Date birthday) {
			this.birthday = birthday;
		}
		public Address getAddress() {
			return address;
		}
		public void setAddress(Address address) {
			this.address = address;
		}
		@Override
		public String toString() {
			return "User [birthday=" + birthday + ", address=" + address + "]";
		}
	}
	
	public static class Address {
		private String name;
		public String getName() {
			return name;
		}
		public void setName(String name) {
			this.name = name;
		}
		@Override
		public String toString() {
			return "Address [name=" + name + "]";
		}
	}
	
}